<template>
  <div class="main-div">

    <Modal
      v-model="speedDialog.model"
      :mask-closable="false"
      title="任务进度查看"
      width="50%"
      :transfer="false"
      @on-cancel="handleBatchInvalidDialogReset"
    >
      <div>
        <el-form ref="speedDialogForm" :model="speedDialogForm" label-width="120px">

          <el-form-item label="进度">
            <el-progress style="margin-top: 6px;" :text-inside="true" :stroke-width="15" :percentage="speedDialogForm.percentage" />
          </el-form-item>
          <el-form-item label="当前环节">
            <Tag color="primary">{{ speedDialogForm.name }}</Tag>
          </el-form-item>
          <el-form-item label="第一处理人">
            <Tag color="primary">{{ speedDialogForm.handler==null?"暂无":speedDialogForm.handler.fullname }}</Tag>
          </el-form-item>
          <el-form-item label="第二处理人">
            <Tag
              v-for="(item,index) in speedDialogForm.candidates"
              :key="index"
              style="margin-left: 2px"
              color="primary"
              @click="delCommonUsers(index)"
            >
              {{ item.fullname }} &nbsp;

            </Tag>

          </el-form-item>

        </el-form>
      </div>
      <div slot="footer" />
    </Modal>
    <Modal
      v-model="batchInvalidDialog.model"
      :mask-closable="false"
      title="意见"
      width="50%"
      :transfer="false"
      @on-cancel="handleBatchInvalidDialogReset"
    >
      <div>
        <el-form ref="batchInvalidDialogForm" :model="batchInvalidDialogForm" label-width="80px">

          <el-form-item label="意见" prop="option">
            <el-input v-model="batchInvalidDialogForm.option" placeholder="作废" />
          </el-form-item>

        </el-form>
      </div>
      <div slot="footer">
        <Button @click="handleBatchInvalidDialogReset">取消</Button>
        <Button type="primary" @click="batchInvalid">确定</Button>
      </div>
    </Modal>

    <Modal
      v-model="batchTransferDialog.model"
      :mask-closable="false"
      title="批量转办"
      width="50%"
      :transfer="false"
      @on-cancel="handleBatchTransferDialogReset"
    >
      <div>
        <el-form ref="batchTransferDialogForm" :model="batchTransferDialogForm" label-width="160px">
          <el-form-item label="是否移除原有处理人">
            <el-switch v-model="batchTransferDialogForm.deleted" />

          </el-form-item>
          <el-form-item label="新处理人">
            <Button
              v-for="(item,index) in addSubTask.usersInfo"
              :key="index"
              v-model="addSubTask.handlerId"
              type="primary"
              style="margin-left: 2px"
              color="primary"
              @click="delCommonUsers(index)"
            >
              {{ item.fullname }} &nbsp;<Icon type="md-close" />

            </Button>
            <Button type="error" @click="selectUsers(0)">
              <Icon type="ios-contact" />
              处理人
            </Button>
          </el-form-item>

        </el-form>
      </div>
      <div slot="footer">
        <Button @click="handleBatchTransferDialogReset">取消</Button>
        <Button type="primary" @click="addBatchTransferHandler">确定</Button>
      </div>
    </Modal>
    <Modal
      v-model="batchHandoverDialog.model"
      :mask-closable="false"
      title="批量交接"
      width="50%"
      :transfer="false"
      @on-cancel="handleBatchHandoverDialogReset"
    >
      <div>
        <el-form ref="batchHandoverDialogForm" :model="batchHandoverDialogForm" label-width="160px">
          <el-form-item label="交接人">
            <Button
              v-for="(item,index) in addSubTask.usersInfo"
              :key="index"
              v-model="addSubTask.handlerId"
              type="primary"
              style="margin-left: 2px"
              color="primary"
              @click="delCommonUsers(index)"
            >
              {{ item.fullname }} &nbsp;<Icon type="md-close" />

            </Button>
            <Button type="error" @click="selectUsers(0)">
              <Icon type="ios-contact" />
              处理人
            </Button>
          </el-form-item>

        </el-form>
      </div>
      <div slot="footer">
        <Button @click="handleBatchHandoverDialogReset">取消</Button>
        <Button type="primary" @click="addBatchHandoverHandler">确定</Button>
      </div>
    </Modal>

    <Modal
      v-model="addSubTask.model"
      :mask-closable="false"
      title="添加虚拟任务"
      width="50%"
      :transfer="false"
      @on-cancel="handleAddSubTaskReset"
    >
      <div>

        <Form ref="addSubTask" :model="addSubTask" :label-width="120" :rules="addSubTaskRuleValidate">
          <FormItem v-model="addSubTask.strategyId" label="策略" prop="strategyId">
            <el-radio v-model="addSubTask.strategyId" label="2">抢占模式</el-radio>
            <el-radio v-model="addSubTask.strategyId" label="1">独占模式</el-radio>

          </FormItem>
          <FormItem
            v-if="addSubTask.strategyId==1"
            v-model="addSubTask.multiPlayerStrategyId"
            label="多人审批的策略"
            prop="multiplayerStrategyId"
          >
            <el-radio v-model="addSubTask.multiPlayerStrategyId" label="1">依次审批</el-radio>
            <br>
            <el-radio v-model="addSubTask.multiPlayerStrategyId" label="2">会签(需所有人审批通过)</el-radio>
            <br>
            <el-radio v-model="addSubTask.multiPlayerStrategyId" label="3">或签(一名审批人同意或者拒绝即可)</el-radio>

          </FormItem>

          <FormItem label="处理人" prop="handlerId">
            <Button
              v-for="(item,index) in addSubTask.usersInfo"
              :key="index"
              v-model="addSubTask.handlerId"
              type="primary"
              style="margin-left: 2px"
              color="primary"
              @click="delCommonUsers(index)"
            >
              {{ item.fullname }} &nbsp;<Icon type="md-close" />

            </Button>
            <Button type="error" @click="selectUsers(0)">
              <Icon type="ios-contact" />
              处理人
            </Button>
            <user-multiple-dialog
              :on-ok="confirmDialogEvent"
              :show.sync="show"
              :exist-data="addSubTask.usersInfo"
              :alias="alias"
            />
          </FormItem>

        </Form>

      </div>
      <div slot="footer">
        <Button @click="handleAddSubTaskReset('addSubTask')">取消</Button>
        <Button type="primary" @click="addSubTaskHandler">确定</Button>
      </div>
    </Modal>
    <Row>
      <Col span="4">
        <Tree :data="categoryData" expand="true" default-expand-all="true" @on-select-change="refreshTask" />
      </Col>
      <Col span="20">
        <Card dis-hover class="task-card">
          <div class="app-container">
            <el-row type="flex" justify="start" style="margin-left: -25px">

              <el-form :inline="true" :model="queryForm" class="demo-form-inline" size="mini">

                <el-form-item label="时间区间">
                  <el-date-picker
                    v-model="queryDate"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    unlink-panels
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :picker-options="pickerOptions"
                    end-placeholder="结束日期"
                  />
                </el-form-item>

                <el-form-item label="发起人">
                  <el-input v-model="queryForm.startUserNo" clearable />
                </el-form-item>
                <el-form-item label="模型名称">
                  <el-input v-model="queryForm.keyWord" clearable />
                </el-form-item>
                <el-form-item style="margin-left: 26px">
                  <el-button type="primary" @click="search">查询</el-button>
                  <el-button type="default" @click="reset">重置</el-button>
                </el-form-item>
              </el-form>
            </el-row>
            <el-row style="margin-bottom: 10px">
              <el-button type="primary" @click="batchCompletedTaskAction()">批量送审</el-button>
              <el-button type="success" @click="batchHandover()">批量交接</el-button>
              <el-button type="primary" @click="batchTransfer()">批量转办</el-button>
              <el-button type="danger" @click="batchInvalidAction()">批量作废</el-button>

            </el-row>

            <el-row class="margin:30px;">
              <el-col>
                <el-table
                  :data="tableData"
                  size="mini"
                  style="width: 100%"
                  :height="tableHeight"
                  border
                  @selection-change="handleSelectionChange"
                >
                  <el-table-column
                    type="selection"
                    fixed
                    width="55"
                  />
                  <el-table-column
                    fixed
                    prop="taskTitle"
                    label="任务标题"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    prop="categoryName"
                    label="所属分类"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    prop="name"
                    label="任务名称"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    prop="priority"
                    label="类型"
                    show-overflow-tooltip
                  >
                    <template slot-scope="scope">
                      <Tag v-if="scope.row.priority==50" color="primary">普通</Tag>
                      <Tag v-else-if="scope.row.priority>50 && scope.row.priority<=100" color="warning">加急</Tag>
                      <Tag v-else color="error">紧急</Tag>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="priority"
                    label="任务池"
                    show-overflow-tooltip
                  >
                    <template slot-scope="scope">
                      <Tag v-if="scope.row.scopeType==null" color="primary">常规任务</Tag>
                      <Tag v-else-if="scope.row.scopeType=='taskPool'" color="warning">虚拟任务</Tag>
                      <Tag v-else color="error">紧急</Tag>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="createTime"
                    label="接受时间"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    prop="dueDate"
                    show-overflow-tooltip
                    label="到期时间"
                  />
                  <el-table-column
                    fixed="right"
                    label="操作"
                    width="180"
                  >
                    <template slot-scope="scope">
                      <el-button type="text" size="small" @click="handleClick(scope.row)">办理</el-button>
                      <el-button type="text" size="small" @click="speedClick(scope.row)">进度</el-button>
                      <!--                      <el-button @click="handleAddSubNodeClick(scope.row)" type="text" size="small">添加任务</el-button>-->
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
            </el-row>
            <el-row type="flex" justify="center">
              <el-pagination
                background
                :current-page="queryForm.page"
                :page-size="queryForm.pageSize"
                layout="total, prev, pager, next, jumper"
                :total="total"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </div>
        </Card>
      </Col>

    </Row>
  </div>

</template>

<script>
// eslint-disable-next-line no-unused-vars
import { getTaskData, getTaskChartData, getBpmnModelCategory, batchTransfer, batchHandover, batchInvalid, batchOperate, processOperate, saveSubTask } from '@/api/analy'
import userMultipleDialog from '@/views/components/org/userMultipleDialog'

export default {
  name: 'Task',
  components: {
    userMultipleDialog
  },

  data() {
    return {
      batchTransferDialog: {
        model: false
      },
      batchTransferDialogForm: {
        deleted: false

      },
      batchHandoverDialog: {
        model: false
      },
      batchHandoverDialogForm: {
        deleted: false

      },
      batchInvalidDialogForm: {
        option: ''
      },
      speedDialogForm: {
        name: '',
        handler: null,
        percentage: 0,
        candidates: null
      },
      batchInvalidDialog: {
        model: false
      },
      speedDialog: {
        model: false
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      show: false,
      existData: [],
      tableData: [],
      multipleSelection: [],
      tableHeight: 450,
      queryDate: [],
      total: 0,
      chartVisible: false,
      chartData: {},
      shopName: [],
      addSubTask: {
        model: false,
        strategyId: '2',
        usersInfo: [],
        parentTaskId: '',
        multiPlayerStrategyId: '1',
        handlerId: ''
      },
      alias: 'addSubTask',
      addSubTaskRuleValidate: {
        handlerId: [
          { required: true, message: '办理人必须填写', trigger: 'blur' }
        ],
        option: [
          { required: true, message: '意见必须填写', trigger: 'blur' }
        ]

      },
      addBatchInvalidRuleValidate: {
        option: [
          { required: true, message: '意见必须填写', trigger: 'blur' }
        ]

      },
      queryForm: {
        name: '',
        startTime: '',
        endTime: '',
        startUserNo: '',
        keyWord: '',
        page: 0,
        limit: 10,
        whereSql: '',
        typeKey: ''
      },
      categoryData: []
    }
  },
  mount() {
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop
  },
  created() {
    this.getData()
  },
  methods: {
    handleBatchTransferReset() {
      this.batchTransferDialogForm.deleted = false
      this.addSubTask.usersInfo = []
    },
    handleBatchTHandoverReset() {
      this.addSubTask.usersInfo = []
    },
    addBatchTransferHandler: function() {
      this.$refs['batchTransferDialogForm'].validate((valid) => {
        if (valid) {
          // const obj = JSON.parse(JSON.stringify(this.addSubTask))
          // delete (obj['usersInfo'])
          // delete (obj['model'])
          var obj = {}
          obj['deleted'] = this.batchTransferDialogForm.deleted
          // eslint-disable-next-line eqeqeq
          if (this.addSubTask.usersInfo.length === 0) {
            this.$message({ 'duration': 800, message: '请选择处理人', type: 'warning', customClass: 'zZindex' })

            return
          }
          const objUser = JSON.parse(JSON.stringify(this.addSubTask))
          obj['userList'] = objUser['usersInfo']

          var tids = []
          this.multipleSelection.forEach((item, index, array) => {
            tids.push(item.id)
          })
          obj['taskIds'] = tids
          batchTransfer(obj).then((response) => {
            if (response.code === 0) {
              this.$message({ 'duration': 800, message: '操作成功', type: 'warning', customClass: 'zZindex' })

              this.getTaskData()
              this.handleBatchTransferDialogReset()
            } else {
              this.$message({ 'duration': 800, message: response.msg, type: 'warning', customClass: 'zZindex' })
            }
          })
        }
      })
    },
    addBatchHandoverHandler: function() {
      this.$refs['batchHandoverDialogForm'].validate((valid) => {
        if (valid) {
          var obj = {}
          if (this.addSubTask.usersInfo.length === 0) {
            this.$message({ 'duration': 800, message: '请选择处理人', type: 'warning', customClass: 'zZindex' })

            return
          }
          const objUser = JSON.parse(JSON.stringify(this.addSubTask))
          obj['userList'] = objUser['usersInfo']
          var tids = []
          this.multipleSelection.forEach((item, index, array) => {
            tids.push(item.id)
          })
          obj['taskIds'] = tids
          batchHandover(obj).then((response) => {
            if (response.code === 0) {
              this.$message({ 'duration': 800, message: '操作成功', type: 'warning', customClass: 'zZindex' })

              this.getTaskData()
              this.handleBatchHandoverDialogReset()
            } else {
              this.$message({ 'duration': 800, message: response.msg, type: 'warning', customClass: 'zZindex' })
            }
          })
        }
      })
    },
    handleBatchTransferDialogReset: function() {
      this.handleBatchTransferReset()
      this.existData = []
      this.batchTransferDialog.model = false
    },

    handleBatchHandoverDialogReset: function() {
      this.handleBatchTHandoverReset()
      this.existData = []
      this.batchHandoverDialog.model = false
    },
    batchTransfer: function() {
      if (this.multipleSelection.length > 0) {
        this.batchTransferDialog.model = true
      } else {
        this.$message({ 'duration': 800, message: '请选择数据', type: 'warning', customClass: 'zZindex' })
      }
    },
    batchHandover: function() {
      if (this.multipleSelection.length > 0) {
        this.batchHandoverDialog.model = true
      } else {
        this.$message({ 'duration': 800, message: '请选择数据', type: 'warning', customClass: 'zZindex' })
      }
    },
    batchInvalidAction: function() {
      if (this.multipleSelection.length > 0) {
        this.batchInvalidDialog.model = true
      } else {
        this.$message({ 'duration': 800, message: '请选择数据', type: 'warning', customClass: 'zZindex' })
      }
    },
    batchCompletedTaskAction: function() {
      if (this.multipleSelection.length > 0) {
        batchOperate(this.multipleSelection).then((response) => {
          if (response.code === 0) {
            this.$message({ 'duration': 800, message: '操作成功', type: 'warning', customClass: 'zZindex' })

            this.getTaskData()
          } else {
            this.$message({ 'duration': 800, message: response.msg, type: 'warning', customClass: 'zZindex' })
          }
        })
      } else {
        this.$message({ 'duration': 800, message: '请选择数据', type: 'warning', customClass: 'zZindex' })
      }
    },
    handleBatchInvalidDialogReset: function() {
      this.batchInvalidDialog.model = false
      this.batchInvalidDialogForm.option = ''
    },

    batchInvalid: function() {
      if (this.multipleSelection.length > 0) {
        var pids = []
        this.multipleSelection.forEach((item, index, array) => {
          pids.push(item.processInstanceId)
        })
        var obj = {}
        obj['pids'] = pids
        obj['option'] = this.batchInvalidDialogForm.option
        batchInvalid(obj).then((response) => {
          if (response.code === 0) {
            this.$message({ 'duration': 800, message: '操作成功', type: 'warning', customClass: 'zZindex' })

            this.getTaskData()
            this.handleBatchInvalidDialogReset()
          } else {
            this.$message({ 'duration': 800, message: response.msg, type: 'warning', customClass: 'zZindex' })
          }
        })
      } else {
        this.$message({ 'duration': 800, message: '请选择数据', type: 'warning', customClass: 'zZindex' })
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    resetQuery: function() {
      this.queryForm.name = ''
      this.queryForm.startUserNo = ''
      this.queryForm.keyWord = ''
      this.queryForm.createTime = ''
      this.queryForm.startTime = ''
      this.queryForm.endTime = ''
      this.queryForm.page = 0
      this.queryDate = []
    },
    delCommonUsers: function(index) {
      this.addSubTask.usersInfo.splice(index, 1)
    },
    confirmDialogEvent: function(data) {
      if (data) {
        this.addSubTask.usersInfo = data
        var str = ''
        for (var i = 0; i < data.length; i++) {
          str += data[i].userNo + ','
        }
        // 去掉最后一个逗号(如果不需要去掉，就不用写)
        if (str.length > 0) {
          str = str.substr(0, str.length - 1)
        }
        this.addSubTask.handlerId = str
      }
    },
    selectUsers: function() {
      this.show = true
    },
    queryFormCreateTime: function(e) {
      if (e) {
        this.queryForm.startTime = e[0]
        this.queryForm.endTime = e[1]
      }
    },
    handleAddSubTaskReset: function() {
      this.handleReset()
      this.existData = []
      this.addSubTask.model = false
    },
    refreshTask: function(data) {
      if (data[0].parentId === '-1') {
        this.queryForm.typeKey = ''
      } else {
        this.queryForm.typeKey = data[0].typeKey
      }
      this.queryForm.createTime = ''
      this.queryDate = []
      this.queryForm.whereSql = ''
      this.getTaskData()
    },
    queryMethod: function() {
      // eslint-disable-next-line no-unused-vars
      var name = this.queryForm.name
      var whereSql = ''
      var createTime = this.queryForm.createTime
      if (createTime) {
        if (createTime[0]) {
          whereSql = "  CREATE_TIME_  between '" + createTime[0] + "' and " + "'" + createTime[1] + "'"
        }
      }
      this.queryForm.whereSql = whereSql
      getTaskData(this.queryForm).then((response) => {
        this.tableData = response.data
        if (response.count.length > 0) {
          this.total = parseInt(response.count)
        } else {
          this.total = 0
        }
      })
    },

    getData: function() {
      getBpmnModelCategory().then((response) => {
        this.categoryData = response.data
      })
      this.getTaskData()
    },
    getTaskData: function() {
      getTaskData(this.queryForm).then((response) => {
        this.tableData = response.data
        if (response.count.length > 0) {
          this.total = parseInt(response.count)
        } else {
          this.total = 0
        }
      })
    },
    handleCurrentChange(val) {
      this.queryForm.page = val
      this.getTaskData()
    },
    handleClick(data) {
      this.$router.push({
        name: 'handleRunTask',
        query: { t: new Date().getTime(), 'taskId': data.id, 'scopeType': data.scopeType }
      })
    },
    speedClick(data) {
      this.speedDialogForm.name = data.name
      processOperate(data.id).then((response) => {
        this.speedDialogForm.handler = response.data.handler
        this.speedDialogForm.candidates = response.data.candidates
        try {
          this.speedDialogForm.percentage = Number(response.data.percentage)
        } catch (e) {
          console.log(e)
        }
      })

      this.speedDialog.model = true
    },
    handleAddSubNodeClick(data) {
      this.addSubTask.model = true
      this.addSubTask.parentTaskId = data.id
    },
    handleReset() {
      this.addSubTask.usersInfo = []
      this.addSubTask.handlerId = ''
      this.addSubTask.strategyId = '1'
    },
    search() {
      this.queryForm.page = 0
      if (this.queryDate) {
        this.queryForm.startTime = this.queryDate[0]
        this.queryForm.endTime = this.queryDate[1]
      }

      this.queryMethod()
    },
    addSubTaskHandler() {
      this.$refs['addSubTask'].validate((valid) => {
        if (valid) {
          const obj = JSON.parse(JSON.stringify(this.addSubTask))
          delete (obj['usersInfo'])
          delete (obj['model'])

          saveSubTask(obj).then((response) => {
            if (response.code === 0) {
              this.$message({ 'duration': 800, message: '操作成功', type: 'warning', customClass: 'zZindex' })

              this.addSubTask.model = false
              this.handleReset()
              this.getTaskData()
            } else {
              this.$message({ 'duration': 800, message: response.msg, type: 'warning', customClass: 'zZindex' })
            }
          })
        }
      })
    },

    reset() {
      this.resetQuery()
      this.getTaskData()
    }

  }

}

</script>
<style lang="scss">
  .task-card {
    margin-top: 10px;
  }

</style>
